#!/bin/bash 
echo "--> Starting composer preparing: prepare_composer.sh..." 
. /vagrant/vagrant/functions.sh

SOURCE_ROOT=/vagrant

# May need to download composer dependencies
if [ ! -e $SOURCE_ROOT/webapp/composer.phar ]; then
    echo "Installing composer.phar..."
    echo "----- IMPORTANT: please manually delete composer.phar if we see failure below ----"
    sudo curl -sS https://getcomposer.org/installer | php
	echo "move composer.phar to $SOURCE_ROOT/webapp/"
	sudo mv composer.phar $SOURCE_ROOT/webapp/
	php -c /etc/php-nodebug.ini composer.phar global require "fxp/composer-asset-plugin:1.1.0"
	# the downloadUrl is invalid , download composer from getcomposer
    # DL_URL=http://${DL_SERVER}/download/composer.phar
    # echo "Downloading composer.phar from $DL_URL"
    # sudo curl -o $SOURCE_ROOT/webapp/composer.phar $DL_URL
    # sudo php $SOURCE_ROOT/webapp/composer.phar install --no-dev
else
    if test `find "${SOURCE_ROOT}/webapp/composer.phar" -mmin +28800`; then
        echo "Composer.phar is older than 20 days, performing self-update"
        sudo php -c /etc/php-nodebug.ini $SOURCE_ROOT/webapp/composer.phar self-update
    else
        echo "Composer.phar is less than 20 days old, update not needed"
    fi
fi

echo Using download server: $DL_SERVER

sudo chmod 600 ${ID_RSA_PATH}
echo "Begin to download vendor file"
if [ ${DL_SERVER} == "ops30.sumilux.com" ]; then
	(cd $SOURCE_ROOT/webapp && sudo php -c /etc/php-nodebug.ini composer.phar install && sudo bower --config.interactive=false install cmis-angularjs-directive#develop -p -F --allow-root)
else
   rsync ${RSYNC_OPTS} --rsh="${RSH_OPTS}" smx@${DL_SERVER}:/opt/www/ops30.sumilux.com/vendor $SOURCE_ROOT/webapp/ 1>/dev/null
fi